<?php

if($_REQUEST['submit']=='Next'  || $_REQUEST['submit']=="DONE" || $_REQUEST['submit']=="Update card")
{
	switch ($_REQUEST['mode'])
		{
			case 'step1':
					// posted vars
					$name	=	strip_tags($_POST['name']);
					$total	=	strip_tags($_POST['total']);
					$daily	=	strip_tags($_POST['daily']);
					$start_date	=	$_POST['start_date'];
					$start_date=explode('-',$start_date);
					$end_date	=	$_POST['end_date'];
					$end_date=explode('-',$end_date);
					//validate flag
					$validate=true;
					$msg=array();
					//validating. nerver change the order of below lines
					if(empty($name))
					{
						$validate=false;
						$msg[]="Campaign Name is missing";
					}
					if(empty($total))
					{
						$validate=false;
						$msg[]="Total Budget is missing";
					}
					elseif(!is_numeric($total))
					{
						$validate=false;
						$msg[]="Total Budget is not numeric";
					}
					if(empty($daily))
					{
						$validate=false;
						$msg[]="Daily Budget is missing";
					}
					elseif(!is_numeric($daily))
					{
						$validate=false;
						$msg[]="Daily Budget is not numeric";
					}
					if(empty($start_date))
					{
						$validate=false;
						$msg[]="Start Date is missing";
					}
					elseif(count($start_date)!=3)
					{
						$validate=false;
						$msg[]="Start Date is invalid";
					}
					if(empty($end_date))
					{
						$validate=false;
						$msg[]="End Date is missing";
					}
					elseif(count($end_date)!=3)
					{
						$validate=false;
						$msg[]="End Date is invalid";
					}
					//convert time string into timstamp
					$start_date=@mktime(0,0,0,$start_date[1],$start_date[2],$start_date[0]);
					$end_date=@mktime(0,0,0,$end_date[1],$end_date[2],$end_date[0]);
					if($end_date<$start_date&&$validate=true)
					{
						$validate=false;
						$msg[]="End Date must be greater than Start Date";
					}
					if($validate)// if validate is true, save data into session and redirect to step2
					{
						mysql_query("DELETE FROM temp_adgroup_ad where siteuserId={$_SESSION[siteuserId]}");
						$campiagn = new stdClass();
						$campiagn->name =$name;
						$campiagn->total=$total;
						$campiagn->daily=$daily;
						$campiagn->start_date=$start_date;
						$campiagn->end_date=$end_date;
						$campiagn->note=strip_tags($_POST['note']);
						$_SESSION[NAME_SESSION_CURRENT_PAGE.'DATA']=$campiagn;
						$step=1;
					}
					else
					{
						$step="";
						$message="";
						foreach($msg as $item)
						{
							$message.="<div style='width:100%;color:red;height:20px;text-align:left;'>".$item."</div>";
						}
						
					}
				break;
			case 'step2':
					$name			=	strip_tags($_REQUEST['add_gr_name']);
					$daily_budget	=	strip_tags($_REQUEST['daily_budget']);
					$network		=	strip_tags($_REQUEST['network']);
					
					//validate flag
					$validate=true;
					$msg=array();
					//validating. nerver change the order of below lines
					if(empty($name))
					{
						$validate=false;
						$msg[]="Group Name is missing";
					}
					if(empty($daily_budget))
					{
						$validate=false;
						$msg[]="Daily Budget is missing";
					}
					elseif(!is_numeric($daily_budget))
					{
						$validate=false;
						$msg[]="Total Budget is not numeric";
					}
					if(empty($network))
					{
						$validate=false;
						$msg[]="Network is missing";
					}
					
					if($validate)// if validate is true, save data into session and redirect to step3
					{
						$data = new stdClass();
						$data->campaign = $_SESSION['CAMPAIGNDATA'];
						//$query_canpaign = 'INSERT INTO adcampaign(camp_name,total_budget,daily_budget,siteuserId,description,start_date,end_date)
							//				values("'.$data->name.'","'.$data->total.'","'.$data->daily.'","'.$_SESSION[siteuserId].'","'.$data->note.'","00-00-00","00-00-00")';
						
						
						if($network=='mobile' || $network=='custom')
						{
							$data->group->adgroup_network="0";
							$data->group->network_type=$network;
							$data->group->network=$network;
						}else{
							$groupNetwork = explode('-', $network);
							$data->group->adgroup_network=$groupNetwork[0];
							$data->group->network_type=$groupNetwork[1];
						}
						$data->group->name=$name;
						$data->group->daily_budget=$daily_budget;
						$_SESSION[NAME_SESSION_CURRENT_PAGE.'DATA']=$data;
						$step=2;
						//$sSql = 'INSERT INTO adgroup(adgroup_name,adgroup_daily_budget,adgroup_network,campaign_id,siteuserId,network_type,network) 
						//values("'.$name.'","'.$daily_budget.'","'.$groupNetwork[0].'","'.$capaign_id.'","'.$_SESSION[siteuserId].'","'.$groupNetwork[1].'","'.$network.'")';
						/*if(mysql_query($sSql)){
							$group_id=mysql_insert_id();
							$campaign = new stdClass();
							$campaign->campaign_id = $capaign_id;
							$campaign->group_id = $group_id;
							$_SESSION[NAME_SESSION_CURRENT_PAGE.'DATA']=$campiagn->group;
							// set active step
							//$_SESSION[NAME_SESSION_CURRENT_PAGE.'ACTIVE_STEP']=3;
							//header('location:create_campaign.php?tab=buy_ads&subMenu=3');
						}*/
						
					}
					else
					{
						$step=1;
						$message="";
						foreach($msg as $item)
						{
							$message.="<div style='width:100%;color:red;height:20px;text-align:left;'>".$item."</div>";
						}
					}
				break;
			case 'step3':
					$data = $_SESSION['CAMPAIGNDATA']->campaign;
					$group=$_SESSION['CAMPAIGNDATA']->group;
					if(is_array( $_REQUEST['ad_group_id']))
					{
						$checked = ' AND id IN ('.implode(",", $_REQUEST["ad_group_id"]).')';
					}
					$query_canpaign = 'INSERT INTO adcampaign(camp_name,total_budget,daily_budget,siteuserId,description,start_date,end_date)
										values("'.$data->name.'","'.$data->total.'","'.$data->daily.'","'.$_SESSION[siteuserId].'","'.$data->note.'","00-00-00","00-00-00")';
					 
					if(mysql_query($query_canpaign))
					{
						$campaign_id=mysql_insert_id();
						$sSql = 'INSERT INTO adgroup(adgroup_name,adgroup_daily_budget,adgroup_network,campaign_id,siteuserId,network_type,network) 
							values("'.$group->name.'","'.$group->daily_budget.'","'.$group->adgroup_network.'","'.$campaign_id.'","'.$_SESSION[siteuserId].'","'.$group->network_type.'","'.$group->network_type.'")';
						
						if(mysql_query($sSql))
						{
							$group_id=mysql_insert_id();
							$query =mysql_query("SELECT * FROM temp_adgroup_ad where  siteuserId={$_SESSION[siteuserId]}.$checked ");
							while($row = mysql_fetch_array($query))
							{
								$sSql = 'INSERT INTO adgroup_ad(adgroup_id,heading,ad_description,dest_url,personal_reference,campaign_id,upload_image,bid,country_id,ad_type)
								VALUES("'.$group_id.'","'.$row['heading'].'","'.$row['ad_description'].'","'.$row['dest_url'].'","'.$row['personal_reference'].'","'.$campaign_id.'","'.$row['upload_image'].'","'.$row['bid'].'","'.$row['country_id'].'","'.$row['ad_type'].'")';
								mysql_query($sSql);
							}
						}
						
					}
					$query = mysql_query("SELECT * FROM payment_method where userId={$_SESSION[siteuserId]} AND userType='A'");
					if(mysql_num_rows($query)>0){
						$step=4;
					}else{
						$step=3;		
					}
			break;	
						
			case 'step4':
					$mgs =array();
					$validate=true;
					if(empty($_REQUEST['card_number']))
					{
						$validate=false;
						$mgs[]="Number isn't a string.";
					}
					if(empty($_REQUEST['cvn']))
					{
						$validate=false;
						$mgs[]="CVN code is incorrect.";
					}
					if(empty($_REQUEST['billing_name']))
					{
						$validate=false;
						$mgs[]="Please enter card name.";
					}
					if(empty($_REQUEST['billing_address']))
					{
						$validate=false;
						$mgs[]="Please enter address.";
					}
					if(empty($_REQUEST['billing_city']))
					{
						$validate=false;
						$mgs[]="Please enter city.";
					}
					if(empty($_REQUEST['billing_state']))
					{
						$validate=false;
						$mgs[]="Please enter state.";
					}
					if(empty($_REQUEST['billing_zip']))
					{
						$validate=false;
						$mgs[]="Please enter zip code.";
					}
				
					if($validate)// if validate is true, save data into session and redirect to step2
					{
						$expire_date = $_REQUEST['card_exp_year']."-".$_REQUEST['card_exp_month']."-01";
						$query='INSERT INTO '.PAYMENT_METHODS.'(userId,userType,payment_method,creadit_card_no,billing_fname,billing_address1,city,state,country,zip,security_code,expire_date)
						values("'.$_SESSION['siteuserId'].'","A","'.$_REQUEST['card_type'].'","'.$_REQUEST['card_number'].'","'.$_REQUEST['billing_name'].'", "'.$_REQUEST['billing_address'].'","'.$_REQUEST['billing_city'].'","'.$_REQUEST['billing_state'].'","'.$_REQUEST['billing_country'].'","'.$_REQUEST['billing_zip'].'","'.$_REQUEST['cvn'].'","'.$expire_date.'")';
						if(mysql_query($query)){
							//$_SESSION[NAME_SESSION_CURRENT_PAGE.'ACTIVE_STEP']=5;
							//header('location:create_campaign.php?tab=buy_ads&subMenu=3');
							$step=4;
						}
					}
					else
					{
						
						$step=3;
						$message="";
						foreach($mgs as $item)
						{
							$message.="<div style='width:100%;color:red;height:20px;text-align:left;'>".$item."</div>";
						}
					}	
			break;
			case 'step5':
			
					
					
					$step="";
					header('location:buying_campaign_manager.php?tab=buy_ads&subMenu=3');
				break;
				
	}
}
else
{
	
	$data= $_SESSION['CAMPAIGNDATA'];
	$path = "campaign_upload/".$_SESSION[siteuserId];
	$msg="";
	
	switch ($_REQUEST['submit'])
	{
		case 'Save':
			
				if($_REQUEST['type']=='mobile')
				{
					$mgs =array();
					$validate=true;
					if(empty($_REQUEST['bid_price']))
					{
						$mgs[]="Please enter an bid price.";
						$validate=false;
					}else 
					{
						$bid_price = $_REQUEST['bid_price'];
						if(!is_numeric($bid_price))
						{
							$msg[]="bid price is not numeric.";
							$validate=false;
						}
						
					}
					
					if(empty($_REQUEST['ad_name']))
					{
						$mgs[]="Please enter ad text.";
						$validate=false;
					}
					if(empty($_REQUEST['destinationUrl']))
					{
						$mgs[]="Please enter destination URL.";
						$validate=false;
					}else{
						if(!stristr($_REQUEST['destinationUrl'], "http://") || !stristr($_REQUEST['destinationUrl'], "."))
						{
							$mgs[]="Invalid URL.";
							$validate=false;
						}
					}
					
					if($_REQUEST['ad_type']=='banner'){
						$row_mobile_ad_image=mysql_fetch_array(mysql_query("select * from temp_image_upload where user_id = '".$_SESSION['siteuserId']."' order by image_id desc LIMIT 1"));
						$ad_image_name=$row_mobile_ad_image['image_name'];
						if(empty($_REQUEST['ad_text']))
						{
							$mgs[]="Please enter ad description.";
							$validate=false;
						}
					}
					$str_country='';
					for($i=0;$i<count($_REQUEST[country_mobile]);$i++)
					{
						if($_REQUEST[country_mobile][$i] != 0 || $_REQUEST[country_mobile][$i] != '')
						{
							
							if(count($_REQUEST[country_mobile])>1)
							{
								if($i==count($_POST[country_mobile])-1)
								{
									$str_country.=$_REQUEST[country_mobile][$i];
								}
								else
								{
									$str_country.=$_REQUEST[country_mobile][$i].",";
								}
							}
							else
							{
								$str_country.=$_REQUEST[country_mobile][$i];
							}
						}
					}
					if($validate){
					$sSql = 'INSERT INTO temp_adgroup_ad(heading,ad_description,dest_url,personal_reference,upload_image,bid,ad_type,country_id,siteuserId,form_id,garbage_val)
						VALUES("","'.$_REQUEST['ad_text'].'","'.$_REQUEST['destinationUrl'].'","'.$_REQUEST['ad_name'].'","'.$ad_image_name.'","'.$_REQUEST['bid_price'].'","'.$_REQUEST['ad_type'].'","'.$str_country.'","'.$_SESSION[siteuserId].'","","")';
					
					mysql_query($sSql);
						echo "<script>
							window.onload = function () {
				    			document.getElementById('ad_text').value='';
				    			document.getElementById('destinationUrl').value='';
				    			document.getElementById('ad_name').value='';
				    			document.getElementById('bid_price').value='';
							}
						</script>";
					}else{
						$message="";
						if(count($mgs)>0){
							foreach($mgs as $item)
							{
								$message.="<div style='width:100%;color:red;height:20px;text-align:left;'>".$item."</div>";
							}
						}
					}
					$step=2;
				}else{
					
					$mgs =array();
					$validate=true;
					if(empty($_REQUEST['txtHeadline']))
					{
						$mgs[]="Please enter an ad headline.";
						$validate=false;
					}
					if($_REQUEST['networkType']=="text")
					{
					if(empty($_REQUEST['text_description']))
					{
						$mgs[]="Please enter ad description.";
						$validate=false;
					}}
					if(empty($_REQUEST['txtAdName']))
					{
						$mgs[]="Please enter ad text.";
						$validate=false;
					}
					if(empty($_REQUEST['txtUrl']))
					{
						$mgs[]="Please enter destination URL.";
						$validate=false;
					}else{
						if(!stristr($_REQUEST['txtUrl'], "http://") || !stristr($_REQUEST['txtUrl'], "."))
						{
							$mgs[]="Invalid URL.";
							$validate=false;
						}
					}
					
					
					if($_REQUEST['networkType'] =='banner' || $_REQUEST['networkType']=='thumbnail')
					{
						if ($_FILES["file"]["error"] > 0)
						{
							$mgs[]= "Error: " . $_FILES["file"]["error"];
							//$validate=false;
						 	
						}
						else
						{
							if(!file_exists($path))	
							{	
								mkdir($path);
								chmod($path,0777);
							}
							$extension =  explode('.',$_FILES["file"]["name"]);
							$file_name = time().".".$extension[1];
							$Path = $path."/".time().".".$extension[1];
							move_uploaded_file($_FILES["file"]["tmp_name"],$Path);
						}
										
					}

					if($validate){
						//$sSql = 'INSERT INTO adgroup_ad(adgroup_id,heading,ad_description,dest_url,personal_reference,campaign_id,upload_image,ad_type,country_id)
						//VALUES("'.$data->group_id.'","'.$_REQUEST['txtHeadline'].'","'.$_REQUEST['text_description'].'","'.$_REQUEST['txtUrl'].'","'.$_REQUEST['txtAdName'].'","'.$data->campaign_id.'","'.$file_name.'","","")';
						$sSql = 'INSERT INTO temp_adgroup_ad(heading,ad_description,dest_url,personal_reference,upload_image,bid,ad_type,country_id,siteuserId,form_id,garbage_val)
						VALUES("'.$_REQUEST['txtHeadline'].'","'.$_REQUEST['text_description'].'","'.$_REQUEST['txtUrl'].'","'.$_REQUEST['txtAdName'].'","'.$file_name.'","0","'.$_REQUEST['ad_type'].'","'.$str_country.'","'.$_SESSION[siteuserId].'","","")';

						if(mysql_query($sSql)){
							
						echo "<script>
							window.onload = function () {
				    			document.getElementById('txtHeadline').value='';
				    			document.getElementById('txtAdName').value='';
				    			document.getElementById('txtUrl').value='';
				    			document.getElementById('text_description').value='';
							}
							
						</script>";
						}
						
						
					}else {
						$message="";
						if(count($mgs)>0){
							foreach($mgs as $item)
							{
								$message.="<div style='width:100%;color:red;height:20px;text-align:left;'>".$item."</div>";
							}
						}
					}
					$step=2;
				}
			break;
		case 'delete';
				$group_id=$_REQUEST['group_id'];
				mysql_query("DELETE FROM temp_adgroup_ad where id={$group_id} ");
				$step=2;
			break;
		default:
		break;
	}

		
}
		
?>